package com.xhj.mybatis.binding;

import cn.hutool.core.lang.ClassScanner;
import com.xhj.mybatis.builder.annotation.MapperAnnotationBuilder;
import com.xhj.mybatis.session.Configuration;
import com.xhj.mybatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * MapperRegistry
 *
 * @author XJks
 * @description Mapper注册中心
 */
public class MapperRegistry {
    /**
     * 全局配置对象
     */
    private Configuration config;

    /**
     * 将已添加的映射器代理加入到 HashMap
     */
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public MapperRegistry(Configuration config) {
        this.config = config;
    }

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public <T> void addMapper(Class<T> type) {
        // 只有 Mapper 是接口类型才能够被添加
        if (type.isInterface()) {
            if (hasMapper(type)) {
                // 如果重复添加了，报错
                throw new RuntimeException("Type " + type + " is already known to the MapperRegistry.");
            }
            // 标记是否加载完成，默认未完成
            boolean loadCompleted = false;
            try {
                // 先将类型和对应的 MapperProxyFactory 放入 knownMappers
                knownMappers.put(type, new MapperProxyFactory<>(type));
                // 必须先添加到 knownMappers，再解析注解，否则解析时可能重复绑定。
                // 创建注解解析器，负责解析 Mapper 接口上的注解。
                MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
                // 解析 Mapper 接口上的注解，完成方法与 SQL 的绑定
                parser.parse();
                // 解析成功，标记为已完成
                loadCompleted = true;
            } finally {
                // 如果解析过程中出错，移除已添加的类型，保证注册表数据一致
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }

    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }

    public void addMappers(String packageName) {
        Set<Class<?>> mapperSet = ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }
}
